#!/bin/bash
set -euo pipefail

SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"

REPO_ROOT_PATH=$SCRIPTPATH/../
MAKE_FILE_PATH=$REPO_ROOT_PATH/Makefile
DOCKERFILE_PATH=$REPO_ROOT_PATH/Dockerfile

VERSION=$(make -s -f $MAKE_FILE_PATH version)
PLATFORMS=("linux/amd64")
GOPROXY="direct|https://proxy.golang.org"


USAGE=$(cat << 'EOM'
  Usage: build-docker-images  [-p <platform pairs>]
  Builds docker images for the platform pair

  Example: build-docker-images -p "linux/amd64,linux/arm"
          Optional:
            -p          Platform pair list (os/architecture) [DEFAULT: linux/amd64]
            -r          IMAGE REPO: set the docker image repo
            -v          VERSION: The application version of the docker image [DEFAULT: output of `make version`]
EOM
)

# Process our input arguments
while getopts "p:r:v:" opt; do
  case ${opt} in
    p ) # Platform Pairs
        IFS=',' read -ra PLATFORMS <<< "$OPTARG"
      ;;
    r ) # Image Repo
        IMAGE_REPO="$OPTARG"
      ;;
    v ) # Image Version
        VERSION="$OPTARG"
      ;;
    \? )
        echo "$USAGE" 1>&2
        exit
      ;;
  esac
done


for os_arch in "${PLATFORMS[@]}"; do
    os=$(echo $os_arch | cut -d'/' -f1)
    arch=$(echo $os_arch | cut -d'/' -f2)

    dockerfile="$DOCKERFILE_PATH"
    if [[ $os == "windows"* ]]; then  
        windows_version=$(echo $os | cut -d'-' -f2) 
        os=$(echo $os | cut -d'-' -f1)
        img_tag="$IMAGE_REPO:$VERSION-$os-$windows_version-$arch"
        dockerfile="${dockerfile}.windows"
        docker build \
            --file "${dockerfile}" \
            --build-arg GOOS=${os} \
            --build-arg GOARCH=${arch} \
            --build-arg WINDOWS_VERSION=${windows_version} \
            --build-arg GOPROXY=${GOPROXY} \
            --tag ${img_tag} \
            ${REPO_ROOT_PATH}
    else
        # Launch a docker buildx instance and save its name so we can terminate it later
        img_tag="$IMAGE_REPO:$VERSION-$os-$arch"
        buildx_instance_name=$(docker buildx create --use)
        docker buildx build \
            --load \
            --file "${dockerfile}" \
            --build-arg GOPROXY=${GOPROXY} \
            --tag ${img_tag} \
            --platform "${os_arch}" \
            ${REPO_ROOT_PATH}
        docker buildx rm ${buildx_instance_name}
    fi
done